package com.ftp.web.spider.service.fileservice;

import com.ftp.web.spider.dao.FileInfoDao;
import com.ftp.web.spider.entity.FileInfo;
import com.ftp.web.spider.utils.SearchFile;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Slf4j
@Service
public class PathFilesService {

    private Logger logger= LoggerFactory.getLogger(PathFilesService.class);

    @Autowired
    private FileInfoDao fileInfoDao;

    @Autowired
    private SearchFile searchFile;

    public void addFilesInfo(File scanPath){
        List<FileInfo> fileInfos=new ArrayList<>();
        searchFile.fileSees(fileInfos,scanPath);
        if(fileInfos.size()>0){
            for(FileInfo fileInfo:fileInfos){
                try {
                    fileInfoDao.insertOneInfo(fileInfo);
                }catch (Exception exception){
                    logger.error("数据{}重复 . Message:{}",fileInfo.toString(),exception.getMessage());
                }

            }
        }
        //fileInfoDao.insertInfo(fileInfos);
    }


    public List<Map<String,FileInfo>> fileDistance(){
        List<FileInfo> fileInfos=fileInfoDao.query();
        List<Map<String,FileInfo>> maps=new ArrayList<>();
        for(FileInfo fileInfo:fileInfos){
            List<FileInfo> screenAfters=fileInfos.stream().filter(fn->fn.getFileName().equals(fileInfo.getFileName())).collect(Collectors.toList());
            if(screenAfters.size()>1){
                Map<String,FileInfo> map=new HashMap();
                for(FileInfo fileInfo1:screenAfters){
                    map.put(fileInfo1.getId()+"-m",fileInfo1);
                }
                maps.add(map);
            }
        }
        return maps;
    }

    public void show(){
        List<Map<String,FileInfo>> maps=this.fileDistance();
        for(Map<String,FileInfo> map:maps){
            for(Map.Entry entry:map.entrySet()){
                String key=entry.getKey().toString();
                FileInfo fileInfo=map.get(key);
                System.out.println(fileInfo.getFileName()+":\t"+fileInfo.getFilePath());
            }
        }
    }

    private void moveFile(String path){
        File file=new File(path);
        File repeat=new File("D:\\repeat");
        if(repeat.exists()){
            repeat.mkdir();
        }
        file.renameTo(new File(repeat+File.separator+file.getName()));
    }


}
